package treemap;

import java.util.Comparator;
import java.util.TreeMap;
import java.util.TreeSet;

public class Demo02 {
    //Treemap  或者 Treeset  存储对象怎么自定义 排序规则

    //方法一  创建 map对象时  传入比较器   实现Comparator接口重写compare方法的类作为参数 传给 map对象
    //方法二  对象实现Comparable接口  重写 compareto方法

    public static void main(String[] args) {
       TreeSet set= new TreeSet<Integer>(new Comparator<Integer>() {
            @Override
            //自定义规则 排序
            public int compare(Integer o1, Integer o2) {
           //     return o1-o2; // 升序
                return o2-o1;
            }
        });

       set.add(2);
       set.add(1);
       set.add(3);
        System.out.println(set);


        //按年龄排序
        TreeSet<Student> set1 = new TreeSet<Student>();
        Student s1 = new Student("张三", 17);
        Student s2= new Student("李四",19);
        Student s3=  new Student("王五",18);
        set1.add(s1);
        set1.add(s2);
        set1.add(s3);
        System.out.println(set1);


        //map
        TreeMap<Student, Integer> treeMap = new TreeMap<>();
        treeMap.put(s1,1);
        treeMap.put(s2,2);
        treeMap.put(s3,3);

        System.out.println(treeMap);


    }
}


//默认修饰符  同包才能访问
class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        //如果 o 是  Studnet的实例对象
            return this.age-((Student) o).getAge();

    }
}
